package com.gome.boot.config.webservice;

import com.gome.boot.config.webservice.endpoint.WebServiceClient;
import com.gome.boot.config.webservice.extension.auth.AuthHTTPConduitConfigurer;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.CXFBusFactory;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduitConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

/**
 * WebService接口基础配置.
 *
 * @author baoxiufeng
 */
public abstract class BaseWebServiceConfig {

    @Autowired
    protected Environment env;

    /**
     * 根据WebService接口的WSDL获取客户端对象.
     *
     * @param wsdlKey WebService接口的WSDL路径Diamond配置KEY.
     * @return WebService接口客户端对象
     */
    protected WebServiceClient createClientByWSDLKey(String wsdlKey) {
        return createClientByWSDL(env.getRequiredProperty(wsdlKey));
    }

    /**
     * 根据WebService接口的WSDL获取客户端对象.
     *
     * @param wsdl WebService接口的WSDL路径.
     * @return WebService接口客户端对象
     */
    protected WebServiceClient createClientByWSDL(String wsdl) {
        return new WebServiceClient(JaxWsDynamicClientFactory.newInstance().createClient(wsdl));
    }

    /**
     * 根据WebService接口的WSDL获取客户端对象.
     *
     * @param wsdlKey WebService接口的WSDL路径Diamond配置KEY.
     * @param username 用户名
     * @param password 密码
     * @return WebService接口客户端对象
     */
    protected WebServiceClient createClientByWSDLKey(String wsdlKey, String username, String password) {
        return createClientByWSDL(env.getRequiredProperty(wsdlKey), username, password);
    }

    /**
     * 根据WebService接口的WSDL获取客户端对象.
     *
     * @param wsdl WebService接口的WSDL路径.
     * @param username 用户名
     * @param password 密码
     * @return WebService接口客户端对象
     */
    protected WebServiceClient createClientByWSDL(String wsdl, String username, String password) {
        Bus bus = CXFBusFactory.getThreadDefaultBus();
        bus.setExtension(new AuthHTTPConduitConfigurer(username, password), HTTPConduitConfigurer.class);
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(bus);
        return new WebServiceClient(dcf.createClient(wsdl));
    }
}
